<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      height="550"
    >
      <el-table-column label="权限" align="left" width="280">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="绑定的规则" width="220" align="left">
        <template slot-scope="{row}">
          <span>{{ row.rule_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限描述" width="420" align="left">
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" align="center" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button v-if="row.status==0" size="mini" type="danger" @click="handleDelete(row, $index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建 -->
    <el-dialog class="data-form-dialog" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px">
        <el-form-item
          label="权限名称"
          prop="name"
          :rules="[
            { required: true, message: '请填写权限名称'},
            { type: 'string', message: '权限名称必需是字符串'},
            { min: 2, max: 32, message: '长度2-32'}
          ]"
        >
          <el-input v-model="temp.name" :disabled="dialogStatus==='update'" placeholder="控制器名+动作名(不含前缀action)" />
        </el-form-item>
        <el-form-item
          v-if="dialogStatus==='update'"
          label="新权限名称"
          prop="new_name"
          :rules="[
            { required: false},
            { type: 'string', message: '权限名称必需是字符串'},
            { min: 0, max: 32, message: '长度2-32'}
          ]"
        >
          <el-input v-model="temp.new_name" placeholder="控制器名+动作名(不含前缀action)" />
        </el-form-item>
        <el-form-item
          label="权限描述"
          prop="description"
          :rules="[
            { required: true, message: '请填写权限描述'},
            { min: 2, max: 128, message: '长度2-128'}
          ]"
        >
          <el-input v-model="temp.description" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="submitLoading" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  fetchPermissionList,
  fetchCreatePermission,
  fetchUpdatePermission
} from '@/api/permission'

export default {
  name: 'Permission',
  components: {},
  data() {
    return {
      tableKey: 0,
      list: [],
      ruleData: {},
      total: 0,
      dialogFormVisible: false,
      dialogStatus: '',
      listLoading: true,
      submitLoading: false, // 提交中
      listQuery: {},
      temp: {
        name: '',
        new_name: '',
        description: ''
      },
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        name: '',
        new_name: '',
        description: ''
      }
    },
    // 创建
    handleCreate() {
      if (this.dialogStatus === 'update') {
        this.resetTemp()
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    handleUpdate(row) {
      this.ruleData = row
      this.temp = Object.assign({ new_name: '' }, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 提交表单
    createData() {
      this.submitLoading = true
      this.submitData()
    },
    updateData() {
      this.submitLoading = true
      this.submintUpdateData()
    },
    submintUpdateData() {
      const _this = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchUpdatePermission(_this.temp).then(() => {
            _this.ruleData.name = _this.temp.new_name ? _this.temp.new_name : _this.ruleData.name
            _this.ruleData.description = _this.temp.description
            _this.dialogFormVisible = false
            _this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            _this.submitLoading = false
          }, () => {
            _this.submitLoading = false
          })
        } else {
          _this.submitLoading = false
        }
      })
    },
    submitData() {
      const _this = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchCreatePermission(_this.temp).then((res) => {
            _this.list.unshift(_this.temp)
            _this.dialogFormVisible = false
            _this.resetTemp()
            _this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })

            _this.submitLoading = false
          }, err => {
            _this.submitLoading = false
          })
        } else {
          _this.submitLoading = false
        }
      })
    },
    getList() {
      fetchPermissionList().then(res => {
        this.listLoading = false
        this.list = res.data.items
      }, rej => {
        this.listLoading = false
      })
    },
    jump(url) {
      this.$router.push(url)
    }
  }
}
</script>

<style>
  .el-dialog {
    width: 550px;
  }

  .cate-icon {
    width: 2.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .filter-container .filter-item {
    display: inline-block;
    vertical-align: middle;
  }
</style>
